package wyh.controller.User;

import com.fasterxml.jackson.databind.ObjectMapper;
import wyh.pojo.User;
import wyh.service.UserService;
import wyh.vo.Result;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@WebServlet("/User/SelectByName")
public class SelectByNameLikeServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ObjectMapper ojmapper = new ObjectMapper();
        // 从 URL 参数中获取 name
        String like = req.getParameter("name");
        String page = req.getParameter("page");
        UserService service = new UserService();
        List<User> list = service.ServicegetByNameLike(like);
        Result result;
        List<User> rootUserList = new ArrayList<>();
        // 过滤出 user_permission  的用户
        if (page.equals("all")) {
            rootUserList = list;
        } else {
            for (User user : list) {
                if (page.equals(user.getUser_permission())) {
                    rootUserList.add(user);
                }
            }
        }
        if (!list.isEmpty()) {
            result = new Result(200, "查询到" + list.size() + "条信息", rootUserList);
        } else {
            result = new Result(500, "未查询到该模糊关键词", null);
        }
        String json = ojmapper.writeValueAsString(result);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(json);
    }
}